package com.shanks.home.util;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;

/**
 * @author Shanks
 * @time 2013.12.16
 */
public class BitmapUtil {

	/**
	 * 获得圆角图片的方法    
	 * @param bitmap
	 * @param roundPx
	 * @return
	 */
	public static Bitmap getRoundCornerBitmap(Bitmap bitmap, float roundPx) {    
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);    
		Canvas canvas = new Canvas(output);    
		final Paint paint = new Paint();    
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());    
		final RectF rectF = new RectF(rect);    
		// 清空画布
		paint.setAntiAlias(true);  // 设置是否抗锯齿  
		canvas.drawARGB(0, 0, 0, 0);
		// 画底部圆角图
		final int color = 0xff424242;
		paint.setColor(color);    
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);    
		// 画bitmap
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));   // 设置两张图片相交时的模式   
		canvas.drawBitmap(bitmap, rect, rect, paint);  
		if (bitmap != output) {
        	bitmap.recycle();
        }   
		return output;    
	} 

	/**
	 * bitmap 旋转
	 * @param bitmap
	 * @param degrees
	 * @return
	 */
	public static Bitmap rotate(Bitmap bitmap, int degrees) {
		if (bitmap != null && degrees != 0) {
			Matrix matrix = new Matrix();
			matrix.setRotate(degrees, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);
			try {
				Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
				if (bitmap != bitmap2) {
					bitmap.recycle();  // 应该显示的释放之前的bitmap
					bitmap = bitmap2;
				}
			} catch (Exception e) {
				
			}
		}
		return bitmap;
	}
}